package com.jstyle.devicenametest.utils;

import android.util.Log;

import java.io.UnsupportedEncodingException;

public class SendData {
    private static final int SHORTENED_LOCAL_NAME = 0x08;
    private static final int COMPLETE_LOCAL_NAME = 0x09;
    public static void crcValue(byte[] value) {
        byte crc = 0;
        for (int i = 0; i < value.length - 1; i++) {
            crc += value[i];
        }
        value[value.length - 1] = (byte) (crc & 0xff);
    }
    public static byte[] reset() {
        byte[] value = new byte[16];
        value[0] = (byte)0x12;
        crcValue(value);
        return value;
    }

    public static byte[] notifyDevice() {
        byte[] value = new byte[16];
        value[0] = (byte)0x4d;
        crcValue(value);
        return value;
    }
    public static String decodeDeviceName(byte[] data) {
        String name = null;
        int fieldLength, fieldName;
        int packetLength = data.length;
        for (int index = 0; index < packetLength; index++) {
            fieldLength = getValue(data[index],0);
            if (fieldLength == 0)
                break;
            fieldName =  getValue(data[++index],0);

            if (fieldName == COMPLETE_LOCAL_NAME
                    || fieldName == SHORTENED_LOCAL_NAME) {
                name = decodeLocalName(data, index + 1, fieldLength - 1);
                break;
            }
            index += fieldLength - 1;
        }
        return name;
    }

    /**
     * Decodes the local name
     */
    public static String decodeLocalName(final byte[] data, final int start,
                                         final int length) {
        try {
            return new String(data, start, length, "UTF-8");
        } catch (final UnsupportedEncodingException e) {
            Log.e("scan", "Unable to convert the complete local name to UTF-8",
                    e);
            return null;
        } catch (final IndexOutOfBoundsException e) {
            Log.e("scan", "Error when reading complete local name", e);
            return null;
        }
    }

    public static int getValue(byte b, int count) {
        return (int) ((b & 0xff) * Math.pow(256, count));
    }
}
